const express = require("express");
const router = express.Router();
const { success, failure } = require("../utils/response");
const { Setting } = require("../models");
const { NotFound } = require("http-errors");
const { setKey, getKey, delKey } = require("../utils/redis");

router.get("/", async (req, res) => {
  try {
    const setting = await Setting.getOne();
    if (!setting) {
      throw new NotFound("设置不存在");
    }
    success(res, "获取设置成功", { setting });
  } catch (error) {
    failure(res, error);
  }
});

// 查询系统信息
router.get("/redis", async (req, res) => {
  try {
    // 缓存的key，定义为：setting
    const cacheKey = "setting";

    // 读取缓存中的数据
    let setting = await getKey(cacheKey);

    // 如果缓存中没有数据，则从数据库中读取数据
    if (!setting) {
      setting = await Setting.findOne();
      if (!setting) {
        throw new NotFound("未找到系统设置，请联系管理员。");
      }

      // 并将数据写入缓存
      await setKey(cacheKey, setting);
    }

    success(res, "查询系统信息成功。", { setting });
  } catch (error) {
    failure(res, error);
  }
});

// 更新系统设置
router.put("/", async (req, res) => {
  try {
    const body = req.body;

    const setting = await Setting.findOne();
    if (!setting) {
      throw new NotFound("未找到系统设置");
    }
    setting.update(body);

    // 删除缓存
    await delKey("setting");

    success(res, "更新系统设置成功。", { setting });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
